﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;



using Corsat.Library.Logic;
using System.Data;
using Corsat.Library;
using System.Threading;

namespace Corsat.Web._2013
{
    public partial class Registration : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Log.Write("Start");

                Session["AccountId"] = null;

                List<Library.Item> Dioceses = Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.Dioceses);
                Dioceses.Insert(0, new Library.Item());
                ddlDiocese.DataSource = Dioceses;
                ddlDiocese.DataTextField = "Value";
                ddlDiocese.DataValueField = "Id";
                ddlDiocese.DataBind();


                List<Library.Item> studyTypes = Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.StudyType);
                studyTypes.Insert(0, new Library.Item());
                ddlStudy.DataSource = studyTypes;
                ddlStudy.DataTextField = "Value";
                ddlStudy.DataValueField = "Id";
                ddlStudy.DataBind();

                List<Library.Item> professions = Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.Profession);
                professions.Insert(0, new Library.Item());
                ddlProfession.DataSource = professions;
                ddlProfession.DataTextField = "Value";
                ddlProfession.DataValueField = "Id";
                ddlProfession.DataBind();

                List<Library.Item> CourseNames = Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.CourseNames);
                CourseNames.Insert(0, new Library.Item());
                ddlCourseNames.DataSource = CourseNames;
                ddlCourseNames.DataTextField = "Value";
                ddlCourseNames.DataValueField = "Id";
                ddlCourseNames.DataBind();


                DataTable dtTelephones = new DataTable();
                for (int i = 0; i < 3; i++)
                    dtTelephones.Rows.Add(dtTelephones.NewRow());

                grdTelephones.DataSource = dtTelephones;
                grdTelephones.DataBind();

                List<ChosenCourse> Courses = new List<ChosenCourse>();

                Session["lstSelectedCourses"] = Courses;

                dlCourses.DataSource = Session["lstSelectedCourses"];
                dlCourses.DataBind();

                pnlChooseCourse.Visible = false;

                Session["CoursesAndDates"] = Corsat.Library.DataManager.Main.GetAllCoursesWithDates();
            }

        }

        protected void lnkRegister_Click(object sender, EventArgs e)
        {
            try
            {
                Account acc = new Account();

                // Just in case that the account is updated.
                acc.AccountId = Session["AccountId"] == null ? 0 : Convert.ToInt32(Session["AccountId"]);

                // Arabic Name
                var ArabicName = tbArabicName_P1.Text
                    + " "
                    + tbArabicName_P2.Text
                    + " "
                    + tbArabicName_P3.Text
                    + " "
                    + tbArabicName_P4.Text;
                acc.ArabicName = ArabicName;

                // SSN
                var SSN = tbSSN.Text;
                acc.SSN = SSN;

                //Email
                acc.Email = tbEmail.Text;

                // Date of Birth
                acc.BirthDate = new DateTime(Convert.ToInt32(tbYear.Text),
                    Convert.ToInt32(ddlMonth.SelectedValue),
                    Convert.ToInt32(tbDay.Text));

                //Diocese
                Library.Item Diocese = new Library.Item();
                if (ddlDiocese.SelectedIndex != -1)
                {
                    Diocese.Id = Convert.ToInt32(ddlDiocese.SelectedItem.Value);
                    Diocese.Value = ddlDiocese.SelectedItem.Text;
                }
                acc.Diocese = Diocese;

                //Church
                Library.Item Church = new Library.Item();
                if (ddlChurch.SelectedIndex != -1)
                {
                    Church.Id = Convert.ToInt32(ddlChurch.SelectedItem.Value);
                    Church.Value = ddlChurch.SelectedItem.Text;
                }
                acc.Church = Church;

                //Study
                Library.Item Study = new Library.Item();
                if (ddlStudy.SelectedIndex != -1)
                {
                    Study.Id = Convert.ToInt32(ddlStudy.SelectedItem.Value);
                    Study.Value = ddlStudy.SelectedItem.Text;
                }
                acc.Study = Study;


                //Study
                Library.Item Profession = new Library.Item();
                if (ddlProfession.SelectedIndex != -1)
                {
                    Profession.Id = Convert.ToInt32(ddlProfession.SelectedItem.Value);
                    Profession.Value = ddlProfession.SelectedItem.Text;
                }
                acc.Profession = Profession;

                // Telephones
                for (int i = 0; i < grdTelephones.Rows.Count; i++)
                {
                    GridViewRow row = grdTelephones.Rows[i];
                    DropDownList ddlTeleType = (DropDownList)row.FindControl("ddlTeleType");
                    TextBox tbNumber = (TextBox)row.FindControl("tbNumber");
                    //CheckBox chkIsDefault = (CheckBox)row.FindControl("chkDefault");

                    if (tbNumber.Text != "" && ddlTeleType.SelectedIndex > -1)
                    {
                        Telephone tele = new Telephone();
                        tele.Number = tbNumber.Text;

                        Library.Item TeleType = new Library.Item();
                        TeleType.Id = Convert.ToInt32(ddlTeleType.SelectedItem.Value);
                        TeleType.Value = ddlTeleType.SelectedItem.Text;

                        tele.Type = TeleType;

                        //TODO: Shoduld remove all the logic regarding that part.
                        tele.IsDefault = false;//chkIsDefault.Checked;

                        if (acc.Telephones == null)
                            acc.Telephones = new List<Telephone>();

                        acc.Telephones.Add(tele);
                    }
                }

                //Is Online Registered
                acc.IsOnlineRegistered = true;

                //Is Activated
                acc.IsActivated = false;

                // Courses
                List<ChosenCourse> lstSelectedCourses = Session["lstSelectedCourses"] as List<ChosenCourse>;

                if (lstSelectedCourses == null || lstSelectedCourses.Count == 0)
                {
                    pnlChooseCourse.Visible = true;
                    var AlertMessage = "يجب إختيار كورس واحد على الأقل لإستكمال الحجز";
                    lblWarning.Text = AlertMessage;
                    lblWarning.Visible = true;
                    return;
                }

                var AccountCoursesNumber = acc.Register(lstSelectedCourses);


                string yearName = WebConfigurationManager.AppSettings["yearName"];

                if (AccountCoursesNumber != 0)
                {
                    pnlRegistrationResult.Visible = true;
                    lblRegistrationResultMessage.Text = @"
<br />
<span style=""color:green; font-size:larger; font-weight:bolder;"">
تم التسجيل بنجاح
</span>
<br />
<hr />
أهـلا بك دارسا معنا
<br />
فى
<br />
<span style=""color:blue; font-size:larger; font-weight:bolder;"">الكورسات المتخصصة - أسقفية الشباب
<br /> "+
       yearName
+@" 
</span>
<br />
<hr />
الرقم الكورساتى الخاص بك

";

                    Session["CorsatId"] = AccountCoursesNumber;
                    Session["AccountId"] = acc.AccountId;

                    lblAccountNumber.Text = AccountCoursesNumber.ToString();

                    lblRegistrationComplementaryMessage.Text = "برجاء الإحتفاظ بهذا الرقم<br />و تسليمه فى الفيلا لإتمام التسجيل و إستلام الكارنيه";

                    this.programmaticModalPopup_RegistrationResult.Show();

                    lnkRegister.Visible = false;
                }

                //Session["AccountId"] = null;
            }
            catch (Exception exc)
            {

            }
        }

        protected void ddlDiocese_SelectedIndexChanged(object sender, EventArgs e)
        {
            object dioceseId = ddlDiocese.SelectedValue;

            if (dioceseId != null)
            {
                List<Library.Item> Churchs = Corsat.Library.DataManager.Main.GetAllItemsByCategoryAndParentItem(Library.DataManager.Category.Churchs, Convert.ToInt32(dioceseId));
                Churchs.Insert(0, new Library.Item());
                ddlChurch.DataSource = Churchs;
                ddlChurch.DataTextField = "Value";
                ddlChurch.DataValueField = "Id";
                ddlChurch.DataBind();
            }

        }

        protected void dlCourses_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            List<ChosenCourse> lstSelectedCourses = Session["lstSelectedCourses"] as List<ChosenCourse>;

            // Handling the case that the Session that is having the lst is expired, so the list will be empty.
            if (lstSelectedCourses != null && lstSelectedCourses.Count > 0)
            {
                lstSelectedCourses.RemoveAt(e.Item.ItemIndex);

                var CoursesCount = hfCoursesCount.Value;


                CoursesCount = (Convert.ToInt32(CoursesCount) - 1).ToString();
                hfCoursesCount.Value = CoursesCount;

                if (Convert.ToInt32(CoursesCount) == 3)
                    btnAddNewCourse.Visible = false;
                else
                    btnAddNewCourse.Visible = true;

            }
            else
                lstSelectedCourses = new List<ChosenCourse>();

            Session["lstSelectedCourses"] = lstSelectedCourses;

            dlCourses.DataSource = Session["lstSelectedCourses"];
            dlCourses.DataBind();
        }

        protected void btnAddCourse_Click(object sender, EventArgs e)
        {

            List<ChosenCourse> lstSelectedCourses = Session["lstSelectedCourses"] as List<ChosenCourse>;
            List<ChosenCourse> results = lstSelectedCourses.FindAll(
               delegate(ChosenCourse c)
               { return c.CourseTitleId == Convert.ToInt32(ddlCourseNames.SelectedValue); }
               );

            DataTable dtCoursesAndDates = new DataTable();

            int tempCourseLevelId = 0;
            if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedIndex > -1)
                tempCourseLevelId = Convert.ToInt32(rdoLevel.SelectedValue);

            if (Session["CoursesAndDates"] != null)
                dtCoursesAndDates = Session["CoursesAndDates"] as DataTable;

            if (ddlCourseNames.SelectedItem.Text == "")
            {
                var AlertMessage = "يجب إختيار كورس للإضافة";
                lblWarning.Text = AlertMessage;
                lblWarning.Visible = true;
            }
            else
                if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedItem == null)
                {
                    var AlertMessage = "يجب تحديد مستوى لهذا الكورس";
                    lblWarning.Text = AlertMessage;
                    lblWarning.Visible = true;
                }
                else
                    if (results.Count > 0
                        &&
                        !(results[0].CourseTitleId == 10
                            &&
                            (results[0].CourseLevelId == 24 && tempCourseLevelId == 25)
                            || (results[0].CourseLevelId == 25 && tempCourseLevelId == 24)
                            )
                        )
                    {



                        var AlertMessage = "لقد تم اختيار هذا الكورس من قبل";
                        lblWarning.Text = AlertMessage;
                        lblWarning.Visible = true;
                        return;

                    }
                    else
                    {
                        lblWarning.Visible = false;

                        ChosenCourse course = new ChosenCourse();

                        course.CourseTitleId = Convert.ToInt32(ddlCourseNames.SelectedValue);

                        if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedIndex > -1)
                            course.CourseLevelId = Convert.ToInt32(rdoLevel.SelectedValue);

                        course.CourseFullName = ddlCourseNames.SelectedItem.Text;

                        if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedIndex > -1)
                            course.CourseFullName += " - " + rdoLevel.SelectedItem.Text;

                        // Fill in the DayId property of the chosen Course.
                        var CourseMatchCondition = "CourseTitleId = " + course.CourseTitleId.ToString();
                        if (course.CourseLevelId != null && course.CourseLevelId != 0)
                            CourseMatchCondition += " AND CourseLevelId = " + course.CourseLevelId.ToString();
                        else
                            CourseMatchCondition += " AND CourseLevelId IS NULL";

                        DataRow[] drCourse = dtCoursesAndDates.Select(CourseMatchCondition);

                        if (drCourse.Length > 0)
                            course.DayId = Convert.ToInt32(drCourse[0]["DayId"]);

                        // Check that there aren't any courses taken in that same Day.
                        List<ChosenCourse> dayResults = lstSelectedCourses.FindAll(
                           delegate(ChosenCourse c)
                           { return c.DayId == Convert.ToInt32(drCourse[0]["DayId"]); }
                           );

                        // Inform the user and terminate the process.
                        if (dayResults.Count > 0)
                        {
                            var AlertMessage = "لقد تم إختيار كورس فى يوم \"" + drCourse[0]["DayName"].ToString() + "\" بالفعل، و لا يمكن إختيار أكثر من كورس فى نفس اليوم";
                            lblWarning.Text = AlertMessage;
                            lblWarning.Visible = true;
                            return;
                        }

                        //Validate Courses Prerequists
                        if (rdoLevel.Items.Count > 0 && rdoLevel.SelectedValue == "23")
                        {
                            bool validationResult = false;
                            validationResult = Account.ValidateCoursePrequists(tbSSN.Text, Convert.ToInt32(ddlCourseNames.SelectedValue), Convert.ToInt32(rdoLevel.SelectedValue));

                            if (validationResult == false)
                            {
                                var AlertMessage = @"لا يمكن إختيار هذا الكورس، لأنك لم تنجح بالمسنوى الأول (أو الكورس المؤهل) لهذا الكورس فى السنة الماضية
                        <br />
                        <br />
                        إذا كنت قد نجحت بالكورس المؤهل لهذا الكورس فى سنة (2011 / 2012)،
                        <br />
                        برجاء إحضار الشهادة التى تثبت ذلك عند تفعيل الحساب و سيتم تسجيلك فى الكورس
                        ";
                                lblWarning.Text = AlertMessage;
                                lblWarning.Visible = true;
                                return;
                            }
                        }

                        // Update the counter of the courses.
                        var CoursesCount = hfCoursesCount.Value;
                        if (String.IsNullOrEmpty(CoursesCount))
                            hfCoursesCount.Value = "1";
                        else
                            if (Convert.ToInt32(CoursesCount) < 3)
                            {
                                CoursesCount = (Convert.ToInt32(CoursesCount) + 1).ToString();
                                hfCoursesCount.Value = CoursesCount;

                                if (Convert.ToInt32(CoursesCount) == 3)
                                    btnAddNewCourse.Visible = false;
                            }

                        lstSelectedCourses.Add(course);

                        Session["lstSelectedCourses"] = lstSelectedCourses;


                        dlCourses.DataSource = Session["lstSelectedCourses"];
                        dlCourses.DataBind();

                        pnlChooseCourse.Visible = false;
                        lblWarning.Visible = false;

                    }
        }

        protected void btnAddNewCourse_Click(object sender, EventArgs e)
        {

            pnlChooseCourse.Visible = true;

            ddlCourseNames.SelectedIndex = -1;
            rdoLevel.Items.Clear();
        }

        protected void ddlCourseNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<Library.Item> CourseLevels = Corsat.Library.DataManager.Main.GetCourseLevels(Convert.ToInt32(ddlCourseNames.SelectedValue));
            rdoLevel.DataSource = CourseLevels;
            rdoLevel.DataTextField = "Value";
            rdoLevel.DataValueField = "Id";
            rdoLevel.DataBind();

        }



        protected void grdTelephones_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex != -1)
            {
                DropDownList ddlTeleType = (DropDownList)e.Row.FindControl("ddlTeleType");
                List<Library.Item> TeleTypes = Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.TelephoneTypes);
                TeleTypes.Insert(0, new Library.Item());
                ddlTeleType.DataSource = TeleTypes;
                ddlTeleType.DataTextField = "Value";
                ddlTeleType.DataValueField = "Id";
                ddlTeleType.DataBind();
            }
        }

        protected void btnLoadAlreadyRegistered_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtAlreadyRegistered_SSN.Text != "")
                {
                    Account tempAccount = Corsat.Library.DataManager.Main.GetAccountBySSN(txtAlreadyRegistered_SSN.Text);

                    if (tempAccount != null)
                    {
                        string[] tempFullNameParts = tempAccount.ArabicName.Split(' ');

                        if (tempFullNameParts.Length != 4)
                        {
                            List<string> fullNameParts = new List<string>();

                            for (int i = 0; i < tempFullNameParts.Length; i++)
                                if (tempFullNameParts[i].Trim() != "")
                                    fullNameParts.Add(tempFullNameParts[i]);

                            if (fullNameParts.Count != 0)
                            {
                                if (fullNameParts.Count > 1) tbArabicName_P1.Text = fullNameParts[0];
                                if (fullNameParts.Count > 2) tbArabicName_P2.Text = fullNameParts[1];
                                if (fullNameParts.Count > 3) tbArabicName_P3.Text = fullNameParts[2];
                                if (fullNameParts.Count > 4) tbArabicName_P4.Text = fullNameParts[3];
                            }
                        }
                        else
                        {
                            tbArabicName_P1.Text = tempFullNameParts[0];
                            tbArabicName_P2.Text = tempFullNameParts[1];
                            tbArabicName_P3.Text = tempFullNameParts[2];
                            tbArabicName_P4.Text = tempFullNameParts[3];
                        }

                        tbSSN.Text = tempAccount.SSN;

                        if (tempAccount.BirthDate != null && tempAccount.BirthDate != new DateTime())
                        {
                            tbDay.Text = tempAccount.BirthDate.Day.ToString();
                            tbYear.Text = tempAccount.BirthDate.Year.ToString();
                            ddlMonth.SelectedItem.Selected = false;
                            ddlMonth.Items.FindByValue(tempAccount.BirthDate.Month.ToString()).Selected = true;
                        }

                        tbEmail.Text = tempAccount.Email;

                        List<ChosenCourse> chosenCourses = new List<ChosenCourse>();

                        for (int i = 0; i < tempAccount.Courses.Count; i++)
                        {
                            ChosenCourse course = new ChosenCourse();
                            course.CourseTitleId = tempAccount.Courses[i].CourseTitle.Id;
                            course.CourseLevelId = tempAccount.Courses[i].CourseLevel.Id;
                            course.DayId = tempAccount.Courses[i].Day.Id;

                            course.CourseFullName = tempAccount.Courses[i].CourseTitle.Value;

                            if (!String.IsNullOrEmpty(tempAccount.Courses[i].CourseLevel.Value))
                                course.CourseFullName += " - " + tempAccount.Courses[i].CourseLevel.Value;

                            chosenCourses.Add(course);
                        }

                        var CoursesCount = hfCoursesCount.Value;

                        CoursesCount = tempAccount.Courses.Count.ToString();
                        hfCoursesCount.Value = CoursesCount;

                        if (Convert.ToInt32(CoursesCount) >= 3)
                            btnAddNewCourse.Visible = false;

                        Session["lstSelectedCourses"] = chosenCourses;

                        dlCourses.DataSource = chosenCourses;
                        dlCourses.DataBind();

                        for (int i = 0; i < tempAccount.Telephones.Count; i++)
                        {
                            GridViewRow row = grdTelephones.Rows[i];
                            DropDownList ddlTeleType = (DropDownList)row.FindControl("ddlTeleType");
                            TextBox tbNumber = (TextBox)row.FindControl("tbNumber");

                            ddlTeleType.SelectedItem.Selected = false;
                            if (tempAccount.Telephones[i].Type.Id != 0)
                                ddlTeleType.Items.FindByValue(tempAccount.Telephones[i].Type.Id.ToString()).Selected = true;

                            tbNumber.Text = tempAccount.Telephones[i].Number;
                        }

                        // Added the AccountId to the Session, as to use it later in re-registering the account, that will be updating it.
                        Session["AccountId"] = tempAccount.AccountId;

                    }
                }
            }
            catch (Exception exc)
            {

            }
        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {

        }

    }
}